package com.flower.enjoyment.flower.controller;

import com.alibaba.fastjson.JSONObject;
import com.flower.enjoyment.flower.base.PageBean;
import com.flower.enjoyment.flower.base.ResultMsg;
import com.flower.enjoyment.flower.entity.ShopInfo;
import com.flower.enjoyment.flower.entity.UserAppointment;
import com.flower.enjoyment.flower.entity.UserAssess;
import com.flower.enjoyment.flower.entity.UserHobby;
import com.flower.enjoyment.flower.entityDo.*;
import com.flower.enjoyment.flower.enumUtils.ResultEnum;
import com.flower.enjoyment.flower.service.OrderInfoService;
import com.flower.enjoyment.flower.service.ShopService;
import com.flower.enjoyment.flower.service.UserAssessService;
import com.flower.enjoyment.flower.service.UserYuYueService;
import com.flower.enjoyment.flower.utils.DateUtil;
import com.flower.enjoyment.flower.utils.RandomUtil;
import com.github.pagehelper.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/shopApi")
@Api(value = "门店信息",description = "门店信息")
public class ShopController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${fileUpload.rootSavePath}")
    private String rootSavePath;

    @Value("${fileUpload.rootHttpPath}")
    private String rootHttpPath;


    @Autowired
    private UserAssessService userAssessService;

    @Autowired
    private ShopService shopService;
    @Autowired
    private UserYuYueService userYuYueService;
    @Autowired
    private OrderInfoService orderInfoService;

    @ApiOperation(value="门店列表", notes="门店列表")
    @ResponseBody
    @GetMapping("/shopList")
    public ResultMsg<ShopInfoDo> getShopList(@ApiParam(value="当前页") @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                             @ApiParam(value="每页条数") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             @ApiParam(value="经度") @RequestParam(value = "lon") String lon,
                                             @ApiParam(value="维度") @RequestParam(value = "lat") String lat){
        PageBean<ShopInfoDo> shopDoPageBean = new PageBean<ShopInfoDo>();
        try {
            Page<ShopInfoDo> shopDoPage = shopService.getCommendShopListByPage(pageNo, pageSize, lon, lat);

            BeanUtils.copyProperties(shopDoPageBean, shopDoPage);
            shopDoPageBean.setItems(shopDoPage.getResult());
        }catch (Exception e){
            logger.error("查询门店列表失败：",e);
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),shopDoPageBean);
    }

    @ApiOperation(value="门店详情", notes="门店详情")
    @ResponseBody
    @GetMapping("/shopDetail")
    public ResultMsg<ShopInfoDo> getShopDetail(@ApiParam(value = "门店ID") @RequestParam( value = "shopId", required = true) String shopId,
                                               @ApiParam(value = "用户ID") @RequestParam( value = "userId", required = true) String userId){
        ShopInfoDo shopInfoDo = shopService.selectByPrimaryKey(shopId);
        int count = orderInfoService.selectCountByUserIdShopId(userId,shopId);
        if (count>0)
            shopInfoDo.setIsAssess(1);
        else
            shopInfoDo.setIsAssess(0);
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), shopInfoDo);
    }

    @ApiOperation(value="门店预约时间段", notes="门店预约时间段")
    @ResponseBody
    @GetMapping("/shopTimeList")
    public ResultMsg<List<String>> getShopTimeList(@ApiParam(value = "门店ID") @RequestParam( value = "shopId", required = true) String shopId,
                                                   @ApiParam(value = "日期（年-月-日）") @RequestParam( value = "shopDate", required = true) String shopDate){
        ShopInfoDo shopInfoDo = shopService.selectByPrimaryKey(shopId);
        if (shopInfoDo == null)
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());


        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), DateUtil.getBetweenTime(shopInfoDo.getBusinessHoursStart(),shopInfoDo.getBusinessHoursEnd()));
    }

    @ApiOperation(value="新增门店信息", notes="新增门店信息")
    @ResponseBody
    @PostMapping(value="/shopAdd")
    public ResultMsg insertShop(@RequestBody ShopInfoDo shopInfoDo){
        try {
            logger.info("----新增门店信息：{}", JSONObject.toJSONString(shopInfoDo));
            int count = shopService.selectCountByUserId(shopInfoDo.getUserId());
            if (count>0){
                return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
            }

            ShopInfo shopInfo = new ShopInfo();
            BeanUtils.copyProperties(shopInfo, shopInfoDo);

            shopService.saveShopInfo(shopInfo, shopInfoDo.getShopImgDoList());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("新增门店信息失败：{}",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),null);
    }

    @ApiOperation(value="上传图片", notes="上传图片")
    @ResponseBody
    @PostMapping(value="/saveShopImg/{type}")
    public ResultMsg saveShopImg(@ApiParam(value = "文件") @RequestParam( value = "file") MultipartFile  file,
                                 @ApiParam(value = "类型，1店铺图片，2评论图片") @PathVariable(value = "type") int type){
        try {
            if(!fileNameIsNull(file)){
                return new ResultMsg(ResultEnum.FILE_ERROR_CODE.getCode());
            }
            String path = shopService.saveShopImg(file, rootSavePath, rootHttpPath,type);
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),path);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("上传图片信息失败：{}",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }
    }


    @ApiOperation(value="服务列表", notes="服务列表")
    @ResponseBody
    @GetMapping("/getServiceTypeList")
    public ResultMsg<ServiceTypeDo> getServiceTypeList(@ApiParam(value="当前页") @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                                           @ApiParam(value="每页条数") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                           @ApiParam(value="商铺ID") @RequestParam(value = "shopId",required = false) String shopId){


            PageBean<ServiceTypeDo> serviceTypeDoPageBean = new PageBean<ServiceTypeDo>();
            try {
                Page<ServiceTypeDo> serviceTypeDoPage = shopService.getServiceTypeListByPage(pageNo, pageSize, shopId);

                BeanUtils.copyProperties(serviceTypeDoPageBean, serviceTypeDoPage);
                serviceTypeDoPageBean.setItems(serviceTypeDoPage.getResult());
            } catch (Exception e) {
                logger.error("获取服务列表失败：", e);
            }
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), serviceTypeDoPageBean);
    }
    @ApiOperation(value="门店服务列表", notes="门店服务列表")
    @ResponseBody
    @GetMapping("/getShopServiceList")
    public ResultMsg<ShopServiceDo> getShopServiceList(@ApiParam(value="当前页") @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                                       @ApiParam(value="每页条数") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                       @ApiParam(value="商铺ID") @RequestParam(value = "shopId") String shopId){


        PageBean<ShopServiceDo> shopServiceDoPageBean = new PageBean<ShopServiceDo>();
        try {
            Page<ShopServiceDo> shopServiceDos = shopService.getShopServiceListByPage(pageNo, pageSize, shopId);

            BeanUtils.copyProperties(shopServiceDoPageBean, shopServiceDos);
            shopServiceDoPageBean.setItems(shopServiceDos.getResult());
        } catch (Exception e) {
            logger.error("获取门店服务列表失败：{}", e.getMessage());
            new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), shopServiceDoPageBean);
    }

    @ApiOperation(value="新增门店服务项目", notes="新增门店服务项目")
    @ResponseBody
    @PostMapping(value="/shopServiceAdd", produces = "text/plain;charset=UTF-8")
    public ResultMsg insertShopService(@RequestBody List<com.flower.enjoyment.flower.entity.ShopService> service){
        try {

            shopService.insertShopService(service);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("新增门店服务项目信息失败：",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),null);
    }
    @ApiOperation(value="删除门店服务项目", notes="删除门店服务项目")
    @ResponseBody
    @DeleteMapping(value="/deleteShopService")
    public ResultMsg insertShopService(@ApiParam(value="店铺服务ID") @RequestParam(value = "id") String id){
        try {
            shopService.deleteShopService(id);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("删除门店服务项目信息失败：",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),null);
    }
    @ApiOperation(value="修改门店信息", notes="修改门店信息")
    @ResponseBody
    @PutMapping("/shopUpdate")
    public ResultMsg updateShop(@RequestBody ShopInfoDo shopInfoDo){

        try {
            ShopInfo shopInfo = new ShopInfo();
            BeanUtils.copyProperties(shopInfo, shopInfoDo);

            shopService.updateShopInfo(shopInfo, shopInfoDo.getShopImgDoList());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("修改门店信息失败：{}",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),null);
    }


    @ApiOperation(value="服务评价", notes="服务评价")
    @ResponseBody
    @PostMapping(value="/insertServiceComment")
    public ResultMsg insertServiceComment(@ApiParam(value = "评论对象") @RequestBody UserAssess userAssess){
        logger.info("服务评价参数：{}",JSONObject.toJSONString(userAssess));
        userAssess.setCreateTime(new Date());
        userAssess.setId(RandomUtil.getUuid());

        try {
            userAssessService.insert(userAssess, userAssess.getAssessImgDos());
        }catch (Exception e){
            logger.error("服务评价发生异常：{}",e);
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),userAssess.getId());
    }
    @ApiOperation(value="删除服务评价", notes="删除服务评价")
    @ResponseBody
    @DeleteMapping(value="/deleteServiceComment")
    public ResultMsg deleteServiceComment(@ApiParam(value = "评论ID") @RequestParam( value = "assessId") String assessId,
                                          @ApiParam(value = "用户ID") @RequestParam( value = "userId") String userId){

        try {
            int result = userAssessService.deleteUserAssess(assessId,userId);
            if (result==0){
                new ResultMsg(ResultEnum.ERROR_CODE.getCode());
            }
        }catch (Exception e){
            logger.error("删除服务评价发生异常：",e);
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),null);
    }

    @ApiOperation(value="预约管理", notes="预约管理")
    @ResponseBody
    @GetMapping("/getAppointmentList")
    public ResultMsg<UserAppointmentDo> getAppointmentList(@ApiParam(value="当前页") @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                             @ApiParam(value="每页条数") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             @ApiParam(value="商铺ID") @RequestParam(value = "shopId") String shopId){

        if(pageSize==1){
            List<UserAppointmentDo> userAppointmentDoList = userYuYueService.selectShopAppointmentList(shopId);
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), userAppointmentDoList);
        }else {
            PageBean<UserAppointmentDo> userAppointmentDoPageBean = new PageBean<UserAppointmentDo>();
            try {
                Page<UserAppointmentDo> userAppointmentDoPage = userYuYueService.selectShopAppointmentListByPage(pageNo, pageSize, shopId);

                BeanUtils.copyProperties(userAppointmentDoPageBean, userAppointmentDoPage);
                userAppointmentDoPageBean.setItems(userAppointmentDoPage.getResult());
            } catch (Exception e) {
                logger.error("获取预约管理分页列表失败：", e);
            }
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), userAppointmentDoPageBean);
        }
    }

    @ApiOperation(value="预约", notes="预约")
    @ResponseBody
    @PostMapping("/insertYuYue")
    public ResultMsg insertYuYue(@RequestBody UserAppointment userAppointment){
        try {
            userAppointment.setId(RandomUtil.getUuid());
            int result = userYuYueService.insert(userAppointment);
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("新增用户预约失败：",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }

    }

    @ApiOperation(value="取消预约", notes="取消预约")
    @ResponseBody
    @PutMapping("/updateYuYue/{id}/{userId}")
    public ResultMsg updateYuYue(@ApiParam(value = "预约ID") @PathVariable("id") String id,
                                 @ApiParam(value = "用户ID") @PathVariable("userId") String userId){
        try {
            UserAppointmentDo appointmentDo = userYuYueService.getUserAppointmentById(id);
            logger.info("用户取消预约{}，根据预约ID获取预约信息：{}",id,appointmentDo);
            if(appointmentDo==null){
                logger.info("未获取到用户预约信息{}",id);
                return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
            }
            UserAppointment userAppointment = new UserAppointment();
            userAppointment.setId(id);
            userAppointment.setStatus(1);
            userAppointment.setUpdateTime(new Date());
            userYuYueService.updateUserAppointmentById(userAppointment);
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),null);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户取消预约失败：",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }

    }

    @ApiOperation(value = "新增点赞", notes = "新增点赞")
    @ResponseBody
    @PostMapping("/insertHobby")
    public ResultMsg insertHobby(@RequestBody UserHobby userHobby) {
        try {
            userHobby.setId(RandomUtil.getUuid());
            int result = userAssessService.insertUserHobby(userHobby);
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("新增用户喜好失败：",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }

    }
    @ApiOperation(value = "删除点赞", notes = "删除点赞")
    @ResponseBody
    @DeleteMapping("/deleteHobby")
    public ResultMsg deleteHobby(@ApiParam(value = "评论ID") @PathVariable("assessId")String assessId,
                                 @ApiParam(value = "用户ID") @PathVariable("userId")String userId) {
        try {
            int result = userAssessService.deleteUserHobby(assessId,userId);
            return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("删除用户喜好失败：",e.getMessage());
            return new ResultMsg(ResultEnum.ERROR_CODE.getCode());
        }

    }

    @ApiOperation(value="店铺收入列表", notes="店铺收入列表")
    @ResponseBody
    @GetMapping("/getShopIncomeList")
    public ResultMsg<OrderInfoDo> getShopIncomeList(@ApiParam(value="当前页") @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                                    @ApiParam(value="每页条数") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                    @ApiParam(value="商铺ID") @RequestParam(value = "shopId") String shopId,
                                                    @ApiParam(value = "类型，值为（today:今日，week:周，month:月，year:年，more：更多）")
                                                          @RequestParam(value = "type") String type){


        PageBean<OrderInfoDo> orderInfoDoPageBean = new PageBean<OrderInfoDo>();
        try {
            Page<OrderInfoDo> orderInfoDoPage = orderInfoService.getShopIncomeOrderListByPage(pageNo, pageSize, shopId, type);

            BeanUtils.copyProperties(orderInfoDoPageBean, orderInfoDoPage);
            orderInfoDoPageBean.setItems(orderInfoDoPage.getResult());
        } catch (Exception e) {
            logger.error("获取门店收入列表失败：{}", e.getMessage());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), orderInfoDoPageBean);
    }


    @ApiOperation(value="大家说", notes="大家说")
    @ResponseBody
    @GetMapping("/everyBodySaysList")
    public ResultMsg<UserAssessDo> everyBodySaysList(@ApiParam(value="当前页") @RequestParam(value = "pageNo",defaultValue = "1",required = false) Integer pageNo,
                                                     @ApiParam(value="每页条数") @RequestParam(value = "pageSize", defaultValue = "10",required = false) Integer pageSize,
                                                     @ApiParam(value = "用户ID") @RequestParam( value = "userId") String userId,
                                                     @ApiParam(value = "门店ID") @RequestParam( value = "shopId") String shopId){
        PageBean<UserAssessDo> userAssessDoPageBean = new PageBean<>();
        try {
            Page<UserAssessDo> userAssessDoList = userAssessService.selectEveryBodySayListByPage(pageNo, pageSize, userId, shopId);
            BeanUtils.copyProperties(userAssessDoPageBean, userAssessDoList);
            userAssessDoPageBean.setItems(userAssessDoList.getResult());
        }catch (Exception e){
            logger.error("获取大家说列表失败：{}", e.getMessage());
        }
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),userAssessDoPageBean);
    }

    public boolean fileNameIsNull(MultipartFile  file){

        if (file.isEmpty() || StringUtils.isBlank(file.getOriginalFilename())) {
            logger.info("图片为空");
            return  false;
        }
        String contentType = file.getContentType();
        if (!contentType.contains("")) {
            logger.info("图片为空");
            return false;
        }

        return true;
    }
}
